//后继节点为中序遍历的下一个节点

//                               1
//                       2                3
//                 4          5       6         7
//            8       9  10     11 12  13  14     15
//8 4 9 2 10 5 11 1 12 6 13 3 14 7 15
//如果该节点有右孩子，那么后继节点为该右子树的最左节点
//如果该节点没有右孩子，则判断该节点是否为父节点的右节点，如果是，则寻找父节点的父节点，依次类推
public class SuccessorNode {
    private static class Node {
        int value;
        Node left;
        Node right;
        Node parent;
        Node(int v){
            value = v;
        }
    }

    public static Node getSuccessorNode(Node node){
        if (node == null){
            return node;
        }
        if (node.right != null){
            return getLeftMost(node.right);
        } else {
            Node parent = node.parent;
            while (parent != null && parent.left != node){
                node = parent;
                parent = node.parent;
            }
            return parent;
        }
    }

    public static Node getLeftMost(Node node){
        if (node == null){
            return node;
        }
        while (node.left != null){
            node = node.left;
        }
        return node;
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.left = new Node(2);
        head.left.parent = head;

        head.right = new Node(3);
        head.right.parent = head;

        head.left.left = new Node(4);
        head.left.left.parent = head.left;

        head.left.right = new Node(5);
        head.left.right.parent = head.left;

        head.right.left = new Node(6);
        head.right.left.parent = head.right;

        head.right.right = new Node(7);
        head.right.right.parent = head.right;

        Node node = getSuccessorNode(head.left.right);
        System.out.println(node.value);
    }
}